package com.crp.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.web.filter.AccessControlFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crp.constants.Constants;
import com.crp.core.util.JsonUtil;
import com.crp.security.StatelessToken;

/**
 * @author jincongmin
 */
public class StatelessAuthcFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	request.setCharacterEncoding("UTF-8");
        try {
         // 1、客户端生成的消息摘要
            String jsonStr = IOUtils.toString(request.getInputStream(), "UTF-8");
            Map<String, Object> map=JsonUtil.parseMap(jsonStr);
            String digest =(String) map.get(Constants.PARAM_DIGEST);
            digest = digest==null?"":digest;
//            System.out.println("digest:"+digest);
            // 2、客户端传入的用户身份
            String secretKey = (String) map.get(Constants.PARAM_KEY);
//            System.out.println("secretKey:"+secretKey);
            // 3、客户端请求的参数列表
            map.remove(Constants.PARAM_DIGEST);
            map.remove(Constants.PARAM_KEY);

            // 4、生成无状态Token
            StatelessToken token = new StatelessToken(secretKey, map, digest.toUpperCase());
            // 5、委托给Realm进行登录
            getSubject(request, response).login(token);
        } catch (Exception e) {
            // 6、登录失败
            onLoginFail(response);
            // TODO: 2015/11/11  增加请求失败的记录
            //e.printStackTrace();
            return false;
        }
        return true;
    }

    // 登录失败
    private void onLoginFail(ServletResponse response) throws IOException {
        PrintWriter writer = null;
        try {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("text/html; charset=utf-8");
            writer = httpResponse.getWriter();
            JSONObject jsonObj=new JSONObject();
            jsonObj.put(Constants.FLAG, "N");
            jsonObj.put(Constants.MESSAGE, "身份认证失败");
            writer.write(jsonObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }
    
    

}
